import { defineStore } from "pinia";
import { ref, computed ,reactive} from "vue"
import arrayToTree
    from "@/utils/arrayToTree";
import { FuncApi } from "@/api";

export default defineStore('func', () => {
    let isInit: boolean = false;
    const allFuncs = reactive<Array<Vm.Func>>([]);
    const allFuncsTreeData = computed<Array<Vm.FuncNode>>(() => {
        return [
            {
                func_id: 0,
                func_name: "Root",
                func_key: "",
                func_fid: -1,
                children: arrayToTree(allFuncs, "func_id", "func_fid"),
            },
        ];
    });
    const init = async () => {
        if (isInit) return;
        allFuncs.push(...await FuncApi.getAll())
        isInit=true;

    }
    const remove = async (func_id: number) => {
        // 发ajax从数据库中删除功能
        await FuncApi.remove(func_id);
        //从allFuncs中删除功能,更新页面
        const i = allFuncs.findIndex((item) => item.func_id === func_id);
        allFuncs.splice(i, 1);
        /**/
    };
    const add = async (model: HttpPayload.Func) => {
        const func_id = await FuncApi.add(model);
        allFuncs.push({ ...model, func_id });
    };
    const update = async (model: HttpPayload.Func) => {
        await FuncApi.update(model);
        const i = allFuncs.findIndex(item => item.func_id === model.func_id);
        allFuncs.splice(i, 1, { ...model })
    }
    return {
        allFuncs,
        allFuncsTreeData,
        remove,
        add,
        update,
        init
    };
});